package org.jinghouyu.caculator.engine.expression;

import java.util.List;

import org.jinghouyu.caculator.engine.Expression;
import org.jinghouyu.caculator.engine.expression.function.FunctionException;

/**
 * 函数表达式 函数表达式，以逗号来分割
 * @author liujingyu
 * 
 */
public abstract class FunctionExpression extends Expression {
	
	private String name = null;
	
	public FunctionExpression(String name) {
		this.name = name;
	}

	@Override
	protected final Object _caculate(Object... values) {
		Range range = parameterCount();
		int length = getLength(values);
		if (range.getStart() > length || range.getEnd() < length) {
			throw new FunctionException(this + " 需要" + range
					+ "个参数，实际有" + length + "个参数");
		}
		return _caculate_(values);
	}

	protected int getLength(Object... values) {
		if (values == null)
			return 0;
		return values.length;
	}

	protected abstract Range parameterCount();

	protected abstract Object _caculate_(Object... values);

	public String toString() {
		StringBuilder sb = new StringBuilder();
		List<Expression> es = getSubExpressions();
		for (int i = 0; i < es.size(); i++) {
			sb.append("" + es.get(i));
			if (i != es.size() - 1) {
				sb.append(",");
			}
		}
		return name + "(" + sb.toString() + ")";
	}

	protected static class Range {
		private int start;
		private int end;
		
		public Range(int start, int end) {
			this.start = start;
			this.end = end;
		}

		public int getStart() {
			return start;
		}

		public void setStart(int start) {
			this.start = start;
		}

		public int getEnd() {
			return end;
		}

		public void setEnd(int end) {
			this.end = end;
		}
		
		public String toString() {
			return "(" + start + "-" + end + ")";
		}
	}
}
